package com.liu.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求前执行");
        String token = request.getHeader("x-token");
        if(null==token){
            //无权访问 返回
            //如果是页面 可以重定向
            //response.sendRedirect("/error.jsp");
            //如果是json格式数据
            response.setContentType("aplication/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.write("{\"code\":0,\"msg\":\"没有token，无权访问！\"}");
            return false;
        }
        //有token 验证token
        return true;//放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("请求后执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("渲染后执行");
    }
}
